package com.fantuan.web;

import java.io.IOException;
import java.sql.SQLException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

/**
 * Cookie中有内容，自动登录
 * @author wangxinning
 *
 */
public class AutoLoginFilter implements Filter{

	private static Log logger = LogFactory.getLog(AutoLoginFilter.class);
	
	private UserAction userAction;
	
	public void destroy() {
		// TODO Auto-generated method stub
		
	}

	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		
		HttpServletRequest httpServletRequest = (HttpServletRequest) request;
		
		//调用自动登录逻辑
		try {
			boolean islogin = userAction.isLogin(httpServletRequest);
			if( !islogin )
			{
				logger.debug("用户未登录");
			}
			else
			{
				logger.debug("已登录用户");
			}
		} catch (SQLException e) {
			
			logger.error("自动登录过滤器出现异常", e);
		}
		
		//返回
		chain.doFilter(request, response);		
	}

	/**
	 * filter和servlet，以这种方式注入
	 */
	public void init(FilterConfig arg0) throws ServletException {
		// TODO Auto-generated method stub
		
		WebApplicationContext wac = WebApplicationContextUtils.getRequiredWebApplicationContext(arg0.getServletContext());
		userAction= (UserAction) wac.getBean("userAction");		
	}
}
